package myClient.sender;

import component.userInformation.UserAttribute;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.Data;
import myClient.session.ClientSession;
import protobuf.protoClass.ProtoMsg;

@Data
public abstract class BaseSender {

    private UserAttribute userAttribute;
    private ClientSession session;

    public boolean isConnected() {
        if (session == null) {
            System.out.println("session is null");
            return false;
        }
        return session.isConnected();
    }

    public boolean isLogin() {
        if (session == null) {
            System.out.println("session is null");
            return false;
        }
        return session.isLogin();
    }

    /**
     * 发送信息
     */
    public void sendMsg(ProtoMsg.Message message) {
        if (session == null || !isConnected()) {
            System.out.println("连接失败");
            return;
        }

        Channel channel = session.getChannel();
        ChannelFuture future = channel.writeAndFlush(message);
        future.addListener(tmpFuture -> {
            //回调
            if (tmpFuture.isSuccess()) {
                sendSucceed(message);
            } else {
                sendFailed(message);
            }
        });
    }

    protected void sendSucceed(ProtoMsg.Message message) {
        System.out.println("发送成功");
    }

    protected void sendFailed(ProtoMsg.Message message) {
        System.out.println("发送失败");
    }

}
